/**
 * Map
 */

function Map(el) {
  Map.HOME = {
    "name"    : "Watoto Wa Baraka",
    "address" : "",
    "point"   : new google.maps.LatLng(-0.8875396524394178, 37.192325592041016)
  };

  // Points.
  var center = new google.maps.LatLng(-1.110, 36.95);

  // Map.
  this.map = new google.maps.Map2(el);
  this.map.addControl(new GLargeMapControl());
  this.map.addControl(new GMapTypeControl());
  this.map.setCenter(center, 9);

  // Geocoder.
  this.geocoder = new GClientGeocoder();

  // Event listener.
  var map = this.map;
  GEvent.addListener(map, "moveend", function() {
    var center = map.getCenter();
    document.getElementById("status").innerHTML = center.toString();
  });

  // Init.
  this.reset();
}

Map.prototype.reset = function(data) {
  this.bounds = new GLatLngBounds();
  this.map.clearOverlays();
  this.markerCount = 0;
  this.addMarker(Map.HOME)
}

Map.prototype.showMarkers = function(data) {
  this.reset();
  for (var key in data) {
    this.geoCodeItem(data[key]);
  }
};

Map.prototype.geoCodeItem = function(item) {
  if (item.address) {
    var self = this;
    this.geocoder.getLatLng(item.address, function(point) {
      if (point) {
        item.point = point;
        self.addMarker(item);
        self.showAllPins();
      }
    });
  }
};

Map.prototype.addMarker = function(item) {
  // Create marker.
  var marker = new GMarker(item.point);

  // Pop-up.
  var map = this.map;
  marker.handler = GEvent.addListener(marker, "click", function() {
    var myHtml = "<b>" + item.name + "</b><div>" + item.address + "</div>";
    map.openInfoWindowHtml(item.point, myHtml);
  });

  // Add to map.
  this.map.addOverlay(marker);
  this.bounds.extend(item.point);
  this.markerCount++;
}

Map.prototype.showAllPins = function() {
  if (this.bounds) {
    var zoom = 11;
    if (this.markerCount > 1) {
      zoom = this.map.getBoundsZoomLevel(this.bounds);
    }
    this.map.setCenter(this.bounds.getCenter(), zoom);
  }
};
